package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

//redis缓存工具类
@Slf4j
@Component
public class CacheClient {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private static final String LOCK_SHOP_KEY = "lock:shop:";
    private final ExecutorService executors= Executors.newFixedThreadPool(10);
    private Boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    //设置过期时间的key的方法
    public void set(String key,Object value, Long Time, TimeUnit TimeUnit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),Time,TimeUnit);
    }
    //设置逻辑过期时间的key的工具
    public void setWithExpire(String key,Object value,Long Time,TimeUnit TimeUnit){
            //设置逻辑过期，封装到redisData对象中
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(TimeUnit.toSeconds(Time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }
    //缓存击穿的工具代码
    public  <R,ID> R queryWithPassThrough(String prefixKey, ID id, Class<R> type, Function<ID,R> function,Long Time,TimeUnit TimeUnit) {
        String cacheKey = prefixKey + id;
        String jsonStr = stringRedisTemplate.opsForValue().get(cacheKey);

        // 缓存命中直接返回
        if (StrUtil.isNotBlank(jsonStr)) {
            return JSONUtil.toBean(jsonStr,type);
        }

        // 处理缓存空值（防止穿透）
        if (Objects.equals(jsonStr, "")) {
            return null;
        }

        // 缓存未命中，直接根据id查询数据库
        R r = function.apply(id);

        // 数据库不存在，缓存空值
        if (r == null) {
           stringRedisTemplate.opsForValue().set(cacheKey,"",RedisConstants.CACHE_NULL_TTL, java.util.concurrent.TimeUnit.MINUTES);
            return null;
        }

        // 缓存非空值
        this.set(cacheKey,r,Time,TimeUnit);
        return r;
    }
    //缓存穿透的工具
    public <R,ID> R queryWithExpire(String prefixKey, ID id, Class<R> type, Function<ID,R> function,Long Time,TimeUnit TimeUnit) {
        String cacheKey = prefixKey + id;

        // 1. 从Redis获取缓存
        String jsonStr = stringRedisTemplate.opsForValue().get(cacheKey);

        // 2. 缓存不存在，返回null（需配合其他策略处理缓存穿透）
        if (StrUtil.isBlank(jsonStr)) {
            return null;
        }

        try {
            // 3. 解析缓存数据
            RedisData redisData = JSONUtil.toBean(jsonStr, RedisData.class);
            R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
            LocalDateTime expireTime = redisData.getExpireTime();

            // 4. 判断缓存是否过期
            if (expireTime.isAfter(LocalDateTime.now())) {
                // 4.1 未过期，直接返回
                return r;
            }

            // 5. 缓存已过期，尝试获取互斥锁
            String lockKey = LOCK_SHOP_KEY + id;
            boolean isLock = tryLock(lockKey);

            // 6. 获取锁成功，开启异步线程重建缓存
            if (isLock) {
                executors.submit(() -> {
                    try {

                        String currentJson = stringRedisTemplate.opsForValue().get(cacheKey);
                        if (!StrUtil.isBlank(currentJson)) {
                            RedisData currentData = JSONUtil.toBean(currentJson, RedisData.class);
                            if (currentData.getExpireTime().isAfter(LocalDateTime.now())) {
                                return; // 其他线程已重建缓存
                            }
                        }
                        //根据id查询数据库
                        R r1 = function.apply(id);
                        this.setWithExpire(cacheKey,r1,Time,TimeUnit);
                    } catch (Exception e) {
                        log.error("重建缓存失败", e);
                    } finally {
                        // 确保锁一定会释放
                        unlock(lockKey);
                    }
                });
            }

            // 7. 不管是否获取锁，都返回旧数据
            return r;

        } catch (Exception e) {
            log.error("解析缓存数据失败", e);
            // 发生异常时，也返回旧数据（如果有）
            return null;
        }
    }
}
